<template>
  <div>
    <!-- 行内表单 -->
    <el-form :inline="true" class="demo-form-inline">
      <!-- 新增按钮 -->
      <el-form-item>
        <el-button type="primary" @click="centerDialogVisible = true">新增</el-button>
      </el-form-item>
    </el-form>

    <!-- 树形表格 有边框 带斑马线 -->
    <el-table :data="tableData" style="width: 100%; margin-bottom: 20px" row-key="id" border default-expand-all stripe>
      <el-table-column prop="name" label="名称" sortable width="180" />
      <el-table-column prop="perms" label="权限编码" sortable width="180" />
      <el-table-column prop="icon" label="图标" sortable width="180" />
      <el-table-column prop="type" label="类型" sortable width="180">
        <!-- 表格行内插槽 参数#default-->
        <template #default="scope">
          <el-tag size="small" v-if="scope.row.type === 0" type="success">目录</el-tag>
          <el-tag size="small" v-else-if="scope.row.type === 1" type="info">菜单</el-tag>
          <el-tag size="small" v-else-if="scope.row.type === 2">按钮</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="path" label="菜单URL" sortable width="180" />
      <el-table-column prop="component" label="菜单组件" sortable width="180" />
      <el-table-column prop="orderNum" label="排序号" sortable width="180" />
      <el-table-column prop="statu" label="状态" sortable width="180">
        <template #default="scope">
          <el-tag size="small" v-if="scope.row.statu === 1" type="success">正常</el-tag>
          <el-tag size="small" v-else-if="scope.row.statu === 0" type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="operate" label="操作" sortable width="180">
        <!-- 表格行内插槽 参数#default-->

        <template #default="scope">
          <!-- 编辑按钮 同时传入一个行id -->
          <el-button type="text" @click="editHandle(scope.row.id)">编辑</el-button>
          <!-- 分割线 -->
          <el-divider direction="vertical" />
          <!-- 气泡式弹出提示框 点击事件是confirm-->
          <el-popconfirm title="确定删除该项？" confirm-button-text="确认" cancel-button-text="取消"
            @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button type="text">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增按钮对话框 -->
    <el-dialog v-model="centerDialogVisible" title="新增" width="600px" align-center :before-close="handleClose">
      <!-- 弹窗内容 -->
      <el-form ref="editFormRef" :model="editForm" :rules="rules" label-width="100px" class="demo-editForm"
        :size="formSize" status-icon>
        <!-- 选择框 -->
        <el-form-item label="上级菜单" prop="parentId">
          <el-select v-model="editForm.parentId" placeholder="请选择上级菜单" width="200px">
            <!-- 循环表单数据中的目录数据 例如系统管理 系统工具等 一级目录 -->

            <template v-for="item in tableData">
              <el-option :label="item.name" :value="item.id" />
              <!-- 循环表单数据中的二级菜单 用户管理 菜单管理等 二级菜单 -->
              <template v-for="menu in item.children">
                <el-option :label="menu.name" :value="menu.id">
                  <!-- 设置显示样式 -->
                  <span>{{ "- " + menu.name }}</span>
                </el-option>
              </template>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="菜单名称" prop="name" label-width="100px">
          <el-input v-model="editForm.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="权限编码" prop="perms" label-width="100px">
          <el-input v-model="editForm.perms" autocomplete="off" />
        </el-form-item>
        <el-form-item label="图标" prop="icon" label-width="100px">
          <el-input v-model="editForm.icon" autocomplete="off" />
        </el-form-item>
        <el-form-item label="菜单URL" prop="path" label-width="100px">
          <el-input v-model="editForm.path" autocomplete="off" />
        </el-form-item>
        <el-form-item label="菜单组件" prop="component" label-width="100px">
          <el-input v-model="editForm.component" autocomplete="off" />
        </el-form-item>
        <!-- 单选框 -->
        <el-form-item label="类型" prop="type" label-width="100px">
          <el-radio-group v-model="editForm.type">
            <el-radio :label="0">目录</el-radio>
            <el-radio :label="1">菜单</el-radio>
            <el-radio :label="2">按钮</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="状态" prop="statu" label-width="100px">
          <el-radio-group v-model="editForm.statu">
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="1">正常</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="排序号" prop="orderNum" label-width="100px">
          <el-input-number v-model="editForm.orderNum" :min="1" label="排序号">1</el-input-number>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm(editFormRef)">
            立即创建
          </el-button>
          <el-button @click="resetForm(editFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { getCurrentInstance, onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { FormInstance, FormRules, Action } from "element-plus";
// 对话框是否显示
const centerDialogVisible = ref(false);
// 表单数据类型接口
interface TableData {
  id: number;
  created?: string;
  updated?: string;
  statu: number;
  parentId: number;
  name: string;
  perms: string;
  component?: string;
  type: number;
  path?: string;
  icon?: string;
  orderNum: number;
  children: TableData[];
}

// 表格数据
const tableData = ref<TableData[]>([]);

// 获取axios实例
const { proxy } = getCurrentInstance() as any;

// 获取列表
function getMenuTree() {
  proxy.$axios.get("/sys/menu/list").then((res: any) => {
    tableData.value = res.data.data;
  });
}
// 在组件挂载后获取数据
onMounted(() => {
  // 调用接口获取菜单树
  getMenuTree();
});

// 表单数据类型
interface EditForm {
  id?: number;
  parentId?: number;
  name?: string;
  perms?: string;
  icon?: string;
  path?: string;
  component?: string;
  type?: number;
  statu?: number;
  orderNum?: number;
}

const formSize = ref("default"); // 表单尺寸
const editFormRef = ref<FormInstance>(); // 创建表单引用实例
const editForm = reactive<EditForm>({
  id: -1,
  name: "",
  perms: "",
  icon: "",
  path: "",
  component: "",
  type: 0,
  statu: 0,
  orderNum: 0,
});

// 表单验证规则
const rules = reactive<FormRules<EditForm>>({
  // 定义表单验证规则
  parentId: [{ required: true, message: "请选择上级菜单", trigger: "blur" }],
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  perms: [{ required: true, message: "请输入权限编码", trigger: "blur" }],
  type: [{ required: true, message: "请选择状态", trigger: "blur" }],
  orderNum: [{ required: true, message: "请填入排序号", trigger: "blur" }],
  statu: [{ required: true, message: "请选择状态", trigger: "blur" }],
});
// 编辑按钮
function editHandle(id: number) {
  // 首先实现数据回显
  proxy.$axios.get("/sys/menu/info/" + id).then((res: any) => {
    // axios获取当前行的数据 同时进行表单的填充
    editForm.id = res.data.data.id;
    editForm.name = res.data.data.name;
    editForm.perms = res.data.data.perms;
    editForm.icon = res.data.data.icon;
    editForm.path = res.data.data.path;
    editForm.component = res.data.data.component;
    editForm.type = res.data.data.type;
    editForm.statu = res.data.data.statu;
    editForm.orderNum = res.data.data.orderNum;
    editForm.parentId = res.data.data.parentId;
  });
  // 显示编辑弹窗
  centerDialogVisible.value = true;
}

// 提交按钮
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 表单验证通过，提交表单数据
      /**
       * 提交表单的方式有两种
       * 1.新增提交
       * 2.编辑提交
       * 通过判断有没有id来区分 默认新建的菜单时 id = -1
       */
      ElMessageBox.alert("确定提交菜单信息？", "菜单编辑", {
        confirmButtonText: "确定",
        type: "warning", // 弹窗类型 警告
        callback: (action: Action) => {
          // 回调函数，用户点击确认后触发
          if (action === "confirm") {
            // 提交信息并接受后端返回的信息
            proxy.$axios
              .post(
                "/sys/menu/" + (editForm.id != -1 ? "update" : "save"),
                editForm
              )
              .then((res: any) => {
                ElMessage({
                  type: "success",
                  message: res.data.msg, // 读取后端返回的信息
                  duration: 1000, // 控制弹出时长
                  onClose: () => {
                    // 关闭弹窗后执行的回调函数 更新表格数据
                    getMenuTree();
                  },
                });
              });
            // 关闭编辑窗口
            centerDialogVisible.value = false;
            // 清空表单数据
            resetForm(editFormRef.value);
          }
        },
      });
    } else {
    }
  });
};

// 表单重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

// 弹窗关闭后操作
function handleClose() {
  // 取消弹窗显示
  centerDialogVisible.value = false;
  // 清除表单内容
  resetForm(editFormRef.value);
}

// 删除菜单选项
function handleDelete(id: number) {
  proxy.$axios.post("/sys/menu/delete/" + id).then((res: any) => {
    ElMessage({
      type: "success",
      message: res.data.msg, // 读取后端返回的信息
      duration: 1000, // 控制弹出时长
      onClose: () => {
        // 关闭弹窗后执行的回调函数 更新表格数据
        getMenuTree();
      },
    });
  });
}
</script>

<style scoped></style>
